import { defineStore } from "pinia";
import { ref } from "vue";
import type { RouteItem } from "@/interface/user/userRouters";
import { useRouter } from "vue-router";

export const useTagBarStore = defineStore("tagBar", () => {
  // 状态定义
  const tagList = ref<RouteItem[]>([]);

  // 获取路由实例 (必须在 setup 函数内部调用)
  const router = useRouter();

  // 操作方法
  const setTagList = (newTag: RouteItem) => {
    const exists = tagList.value.some(item => item.path === newTag.path);
    if (!exists) {
      tagList.value.push(newTag);
      console.log("添加tagList成功", tagList.value);
    }
  };

  const deletTagList = (targetTag: RouteItem, currentRoute: RouteItem) => {
    const index = tagList.value.findIndex(item => item.path === targetTag.path);

    if (index === -1) return;

    // 删除标签
    tagList.value.splice(index, 1);

    // 处理路由跳转
    if (currentRoute.path === targetTag.path) {
      if (tagList.value.length === 0) {
        router.push("/");
      } else {
        const targetIndex = Math.max(index - 1, 0);
        router.push(tagList.value[targetIndex].path);
      }
    }
  };

  return {
    tagList,
    setTagList,
    deletTagList
  };
}, {
  persist: {
    enabled: true,
    strategies: [
      {
        storage: localStorage,
        paths: ["tagList"]
      }
    ]
  }
});
